package com.example.campuslink.viewModel

import android.content.Intent
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.invitation.InvitationTable
import com.example.campuslink.commen.db.message.MessageTable
import com.example.campuslink.commen.db.school.SchoolInfoTable
import com.example.campuslink.commen.db.userNumber.UserNumberTable
import com.example.campuslink.commen.enums.MessageTypeEnum
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpKey
import com.example.campuslink.commen.tools.putExtraKey
import com.example.campuslink.ui.activity.InvitationDetailActivity
import com.example.campuslink.ui.activity.search.SearchMainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainFragmentViewModel : BaseViewModel() {
    private val _schoolAllInvitation = MutableLiveData<List<InvitationTable>>(mutableListOf())
    val schoolAllInvitation get() = _schoolAllInvitation
    var userNumberInfo = UserNumberTable()
    var schoolInfo = SchoolInfoTable()
    private val _getInvitationType = MutableLiveData<String>("发现")
    val getInvitationType get() = _getInvitationType
    private val _topicTableType = MutableLiveData<String>("全部")
    val topicTableType get() = _topicTableType
    fun setTopicTableType(type: String) {
        _topicTableType.postValue(type)
    }

    fun setGetInvitationType(type: String) {
        _getInvitationType.postValue(type)
    }

    fun getAttentionInvitation() {
        val temp = mutableListOf<InvitationTable>()
        viewModelScope.launch(Dispatchers.IO) {
            userNumberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
            )!!
            schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(userNumberInfo.schoolName)
            val attentionNumber = userNumberInfo.followList
            schoolInfo.mainInvitationList.forEach {
                if (attentionNumber.contains(it.userNumber)) {
                    temp.add(it)
                }
            }
            schoolInfo.shoppingInvitationList.forEach {
                if (attentionNumber.contains(it.userNumber)) {
                    temp.add(it)
                }
            }
            _schoolAllInvitation.postValue(temp)
        }
    }

    fun getFansInvitation() {
        val temp = mutableListOf<InvitationTable>()
        viewModelScope.launch(Dispatchers.IO) {
            userNumberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
            )!!
            schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(userNumberInfo.schoolName)
            val fansNumber = userNumberInfo.fansList
            schoolInfo.mainInvitationList.forEach {
                if (fansNumber.contains(it.userNumber)) {
                    temp.add(it)
                }
            }
            schoolInfo.shoppingInvitationList.forEach {
                if (fansNumber.contains(it.userNumber)) {
                    temp.add(it)
                }
            }
            _schoolAllInvitation.postValue(temp)
        }
    }

    fun getInvitation(type: String) {
        val temp = mutableListOf<InvitationTable>()
        viewModelScope.launch(Dispatchers.IO) {
            userNumberInfo = userNumberDao.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
            )!!
            schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(userNumberInfo.schoolName)
            if (type == "全部") {
                _schoolAllInvitation.postValue(schoolInfo.mainInvitationList)
            } else {
                schoolInfo.mainInvitationList.forEach {
//                    Log.i("TAG", "getInvitation: ${it}")
                    if (it.invitationType.contains(type)) {
                        temp.add(it)
                    }
                }
                _schoolAllInvitation.postValue(temp)
            }

        }
    }

    private val _topicTableIndex = MutableLiveData<Int>(0)
    val topicTableIndex get() = _topicTableIndex
    fun setTopicTableIndex(index: Int) {
        _topicTableIndex.postValue(index)
    }

    fun jumpToSearchActivity() {
        startActivity(Intent(), targetClass = SearchMainActivity::class.java)
    }

    fun unCollection(invitation: InvitationTable) {

        viewModelScope.launch(Dispatchers.IO) {
//            val invitation = invitationDao.getInvitationById(invitation1.id, invitation1.userNumber)
            val userNumber =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            invitation?.collectionThisInvitationNumber?.remove(
                Sp.getString(
                    context,
                    SpKey.USER_NUMBER.key,
                    ""
                ) ?: ""
            )
            userNumber?.collectList?.removeAll { it.id == invitation.id && it.userNumber == invitation.userNumber }
            userNumber?.browseList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }

            userNumber?.publishList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }
            invitationDao.updateInvitation(invitation ?: return@launch)
            userNumberDao.updateUserNumber(userNumber ?: return@launch)
            schoolInfo.mainInvitationList.forEach {
                if (it.id == invitation.id && it.userNumber == it.userNumber) {
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                }
            }
            schoolInfoDao.updateSchoolInfo(schoolInfo)
            getInvitation(_topicTableType.value ?: "全部")
        }
    }

    fun collection(invitation: InvitationTable) {

        viewModelScope.launch(Dispatchers.IO) {
            val userNumber =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            val schoolInfoTable =
                schoolInfoDao.getSchoolInfoBySchoolName(userNumber?.schoolName ?: "")
            if (userNumber?.collectList == null) {
                userNumber?.collectList = mutableListOf()
            }
            if (invitation?.collectionThisInvitationNumber == null) {
                invitation?.collectionThisInvitationNumber = mutableListOf()
            }
            if (schoolInfoTable?.messageList == null) {
                schoolInfoTable?.messageList = mutableListOf()
            }
//            userNumber?.collectList?.remove(invitation)
            userNumber?.collectList?.removeAll { it.id == invitation.id && it.userNumber == invitation.userNumber }
            invitation?.collectionThisInvitationNumber?.remove(
                Sp.getString(
                    context,
                    SpKey.USER_NUMBER.key,
                    ""
                ) ?: ""
            )

            if (invitation?.userNumber != Sp.getString(context, SpKey.USER_NUMBER.key, "")) {
                var messageTable = MessageTable()
//                messageTable.id = messageDao.getMaxId() ?: 0 + 1
                messageTable.messageImage = invitation?.invitationImage?.get(0) ?: ""
                messageTable.invitationId = invitation?.id ?: 0
                messageTable.messageTime = System.currentTimeMillis()
                messageTable.messageType = MessageTypeEnum.BE_LOVE_INVITATION.value
                messageTable.sendNumber = Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                messageTable.handNumber = invitation?.userNumber ?: ""
                messageTable.messageContent =
                    "用户${Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""}收藏了你的帖子"
                messageDao.insertMessage(messageTable)
                schoolInfoTable?.messageList?.add(messageTable)
                schoolInfoDao.updateSchoolInfo(schoolInfoTable ?: return@launch)
            }



            userNumber?.collectList?.add(invitation)
            invitation?.collectionThisInvitationNumber?.add(
                Sp.getString(
                    context,
                    SpKey.USER_NUMBER.key,
                    ""
                ) ?: ""
            )
            invitationDao.updateInvitation(invitation ?: return@launch)
            userNumberDao.updateUserNumber(userNumber ?: return@launch)
            schoolInfo.mainInvitationList.forEach {

                if (it.id == invitation.id && it.userNumber == it.userNumber) {
                    Log.i("TAG", "collection: ${it}")
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    Log.i("TAG", "collection: ${it}")
                }
            }
            userNumber?.browseList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
//                    userNumber?.browseList?.remove(it)
//                    userNumber?.browseList?.add(invitation)
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }

            userNumber?.publishList?.forEach {
                if (it.id == invitation.id && it.userNumber == invitation.userNumber) {
//                    it.copy()
//                    it.copy(collectionThisInvitationNumber = invitation.collectionThisInvitationNumber)
                    it.collectionThisInvitationNumber = invitation.collectionThisInvitationNumber
                    it.invitationParentCommend = invitation.invitationParentCommend
                    it.invitationChildrenCommend = invitation.invitationChildrenCommend
                }
            }
            userNumberDao?.updateUserNumber(userNumber ?: return@launch)
            schoolInfoDao.updateSchoolInfo(schoolInfo)
            getInvitation(_topicTableType.value ?: "全部")

        }
    }

    fun addBrowser(invitation: InvitationTable) {
        viewModelScope.launch(Dispatchers.IO) {
            val userNumber =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            if (userNumber?.browseList == null) {
                userNumber?.browseList = mutableListOf()
            }
            userNumber?.browseList?.removeAll { it.id == invitation.id && it.userNumber == invitation.userNumber }
            userNumber?.browseList?.add(invitation)
            userNumberDao.updateUserNumber(userNumber ?: return@launch)
        }
    }

    fun jumpToInvitationDetailActivity(invitation: InvitationTable) {
        Sp.setString(context, SpKey.INVITATION_NUMBER.key, invitation.userNumber)
        Sp.setInt(context, SpKey.INVITATION_ID.key, invitation.id)
        startActivity(Intent().apply {
            putExtra(putExtraKey.INVITATION.key, invitation)
        }, targetClass = InvitationDetailActivity::class.java)
    }
}